package co.za.itweb.itwebafrica;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


@SuppressLint({ "WorldReadableFiles" })
public class FirstScreen extends FragmentActivity {
	 static String[] feeds = {
		        "http://itweb.mobi/feed/itwebafrica/_load_africa.php?source=android&tag=latestnews",
		        "http://itweb.mobi/feed/itwebafrica/_load_africa.php?source=android&tag=editorspick",
		        "http://itweb.mobi/feed/itwebafrica/_load_africa.php?source=android&tag=readerschoice",
		        "http://itweb.mobi/feed/itwebafrica/_load_africa.php?source=android&tag=companynews",
			    "http://itweb.mobi/feed/itwebafrica/_load_africa.php?source=android&tag=video"
		
			};
	 
	 
	 
	 static String[] feedslocal = {
			"latestnews.xml",
		    "editorspick.xml",
		    "readerschoice.xml",
		    "companynews.xml",
		    "video.xml"
		};
	 
	 static String[] feedslocalnames = {
			"Latest News",
		    "Editors Pick",
		    "Readers Choice",
		    "Company News",
		    "Video"
		};
	
	 
	 
	ArrayAdapter<String> adapter;
	static Dialog dialog;
	public static int feedValue;

	 GridAdapter favadapter;
	ArrayList<String> updated;
	
	public ProgressDialog pd;

	public static boolean firstRun;
	
	
	
	static Vector<RSSFeed> fList = new Vector<RSSFeed>(0);
	
	static Vector<RSSFeed> FavoriteList = new Vector<RSSFeed>(0);
	
	FavoriteTask ft;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		
		if( fList.size()==0){

			Intent intent = new Intent(getApplicationContext(), AfricaActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivityForResult(intent,2);

	    }else{
	    	populate();
	    }
	}
	
	public void populate(){

		
		ListView listView = (ListView) findViewById(R.id.mylist);
		String[] values = new String[fList.size()];

		for (int r = 0; r < values.length; r++) {
			if (r == 0) {
				values[r] = "Latest News";
			}
			if (r == 1) {
				values[r] = "Editor's pick";
			}
			if (r == 2) {
				values[r] = "Reader's Choice";
			}
			if (r == 3) {
				values[r] = "Company News";
			}
			if (r == 4) {
				values[r] = "Video";
			}
			
		}

		
		LinearLayout layout = (LinearLayout) findViewById(R.id.cell1);//.findViewById(R.id.title)


	    
		
	    int colors[] =  {Color.parseColor("#ee3126"),Color.parseColor("#9c1e17")};
		GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,colors);
		layout.setBackgroundDrawable(grad);
		

        ImageButton favorites=(ImageButton) findViewById(R.id.cell1).findViewById(R.id.favorites);
        ImageButton refresh=(ImageButton) findViewById(R.id.cell1).findViewById(R.id.refresh);
        ImageButton info=(ImageButton) findViewById(R.id.cell1).findViewById(R.id.info);
        
        

		 favorites.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog = new Dialog(FirstScreen.this);
					dialog.setContentView(R.layout.dialog_favorites);
					dialog.setTitle("ITWeb Africa Favorites");
					dialog.setCancelable(true);
					Button buttonclose = (Button) dialog.findViewById(R.id.closebutton);
					buttonclose.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {

							dialog.dismiss();
						}
					});
					dialog.show();
					showFavourites();
				}
			});
		 
		 refresh.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					
					Intent intent = new Intent(getApplicationContext(), Refresh.class);
					startActivityForResult(intent, 1);

					
				}
			});
		 
		 
		 info.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					
					Intent intent = new Intent(getApplicationContext(), DialogActivity.class);
					startActivity(intent);
					
		
				}
			});
		 
		
		
		adapter = new ArrayAdapter<String>(this, R.layout.rowlayout,
				R.id.label, values);

		// Assign adapter to ListView
		listView.setAdapter(adapter);

		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				Intent intent = new Intent(getApplicationContext(), SingleFeed.class);
				feedValue = position;
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		});
		
		if(firstRun==true){
		
			Intent intent = new Intent(getApplicationContext(), Latest.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			firstRun=false;
		}
			
    
	}
	
	
	@Override
	public void onResume() {
		super.onResume();
		
		populate();
		
	}

	
	

	private void showFavourites() {
		if (dialog.isShowing()) {
			String[] favorites = null;
			ListView listView2 = (ListView) dialog
					.findViewById(R.id.myfavorites);

			SharedPreferences myPrefs = getSharedPreferences(
					SingleNews.PREFS_NAME, MODE_WORLD_READABLE);
			String prefName = myPrefs.getString("co.za.itweb.itwebafrica", "title");
			prefName = prefName.replaceAll("/", "");

		
			JSONArray dat;
			try {
				dat = new JSONArray(prefName);

				favorites = new String[dat.length()];
			
				for (int t = 0; t < dat.length(); t++) {
					try {
						String obj = dat.getJSONObject(t).getString("title")
								+ "|" + dat.getJSONObject(t).getString("id")
								+ "|" + dat.getJSONObject(t).getString("feed");
						favorites[t] = obj;
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			} catch (JSONException e1) {
				e1.printStackTrace();
			}

			if (favorites != null) {
				favadapter = new GridAdapter(this, favorites);
				listView2.setAdapter(favadapter);

			} else {
				Toast.makeText(getApplicationContext(), "No feeds added",
						Toast.LENGTH_SHORT).show();
				dialog.dismiss();
			}

		}

	}

	public class GridAdapter extends BaseAdapter {
		String[] separated;
		private FragmentActivity activity;
		public String[] data;
		public LayoutInflater inflater = null;
		public TextView titletext;
		public ImageLoader imageLoader;
		ArrayList<String> list = new ArrayList<String>();
		JSONArray jsonArray;

		public GridAdapter(FragmentActivity a, String[] d) {
			activity = a;
			data = d;
			imageLoader = new ImageLoader(activity.getApplicationContext());
			inflater = (LayoutInflater) activity
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		}

		public int getCount() {
			return data.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View vi = convertView;
			if (convertView == null)
				vi = inflater.inflate(R.layout.gridbanners, null);
			 separated = data[position].split("\\|");
			titletext = (TextView) vi.findViewById(R.id.texttitle);
			ImageButton erasebutton = (ImageButton) vi
					.findViewById(R.id.erasebutton);
			titletext.setText(separated[0]);
			titletext.setTag(separated[1]);
			titletext.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					ft = new FavoriteTask(FirstScreen.this,v.getTag().toString());
					ft.execute();
					FirstScreen.dialog.dismiss();

				}
			});
			erasebutton.setTag(position);

			erasebutton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					JSONArray JArray;
					try {
						SharedPreferences myPrefs = getSharedPreferences(SingleNews.PREFS_NAME,
								MODE_WORLD_READABLE);
						String prefName = myPrefs.getString("co.za.itweb.itwebafrica", "title");

						
							JArray = new JSONArray(prefName);
						
						List<Object> list = new ArrayList<Object>();
						
						for (int i=0; i<JArray.length(); i++) {
						    list.add( JArray.get(i) );
						}
						
						if(list.size()>0){
							for (int i=0; i<list.size(); i++) {
								if(Integer.parseInt(v.getTag().toString())==i  ){
									list.remove(i);
								}
							}
							    
							JSONArray jsArray = new JSONArray(list);
							
							StringBuilder buf = new StringBuilder();

							buf.append(jsArray).append("\n");

							SharedPreferences settings = getSharedPreferences(SingleNews.PREFS_NAME, 0);
							SharedPreferences.Editor editor = settings.edit();
							editor.clear();

							// SharedPreferences.Editor editor =
							// getSharedPreferences(MODE_WORLD_READABLE).edit();
							editor.putString("co.za.itweb.itwebafrica", buf.toString());
							editor.commit();
							showFavourites();
							}
						
						
						
					}catch (JSONException e) {
						e.printStackTrace();
						Toast.makeText(getApplicationContext(),
								"Sorry there has been a problem with erasing your favorite news...", Toast.LENGTH_SHORT).show();
					}


				}

			});

			return vi;
		}
	}

	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
	

		if (requestCode == 1) {

			if (resultCode == RESULT_OK) {
				adapter.notifyDataSetChanged();
				Toast.makeText(getApplicationContext(),
						"News are refreshed...", Toast.LENGTH_SHORT).show();
				//Intent intent = new Intent(getApplicationContext(), ItWebLiteActivity.class);
				//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				//startActivityForResult(intent,3);
			}

			if (resultCode == RESULT_CANCELED) {
				Toast.makeText(getApplicationContext(),
						"There has been a mistake while refreshing...", Toast.LENGTH_LONG).show();
				fList.clear();
				finish();

			}
			
			
		}
			if (requestCode ==2) {
				if (resultCode == RESULT_OK) {
//					firstRun=true;
//					populate();
					Intent intent = new Intent(getApplicationContext(), Splash2.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivityForResult(intent,3);

				}
			
				
				if (resultCode == RESULT_CANCELED) {
					fList.clear();
					finish();
				}
			}
			if (requestCode ==3) {
				if (resultCode == RESULT_OK) {
					firstRun=true;
					populate();

				}
			
				
				if (resultCode == RESULT_CANCELED) {
					fList.clear();
					finish();
				}
				
			}
		
	}
	public void updateFavs() {
		if (updated.size() > 0) {
			SharedPreferences settings = getSharedPreferences(
					SingleNews.PREFS_NAME, 0);
			SharedPreferences.Editor editor = settings.edit();
			editor.clear();
			editor.commit();
			JSONArray JArray = new JSONArray();

			try {
				for (int y = 0; y < updated.size(); y++) {
					String[] newjson = updated.get(y).split("\\|");
					JSONObject jObjectType = new JSONObject();
					jObjectType.put("feed", 1);
					jObjectType.put("id", newjson[2]);
					jObjectType.put("title", newjson[0]);

					JArray.put(jObjectType);


				}

				StringBuilder buf = new StringBuilder();

				buf.append(JArray).append("\n");

				SharedPreferences settings3 = getSharedPreferences(
						SingleNews.PREFS_NAME, 0);
				SharedPreferences.Editor editor3 = settings3.edit();

				editor3.putString("co.za.itweb.itwebafrica", buf.toString());
				editor3.commit();
				updated.clear();
				favadapter.notifyDataSetChanged();

			} catch (JSONException e) {
				e.printStackTrace();
			}

		} else {
			SharedPreferences settings2 = getSharedPreferences(
					SingleNews.PREFS_NAME, 0);
			SharedPreferences.Editor editor2 = settings2.edit();
			editor2.clear();
			editor2.commit();

		}
	}
	
	@Override
    public void startActivityForResult(Intent intent, int requestCode) {
        intent.putExtra("requestCode", requestCode);
        super.startActivityForResult(intent, requestCode);
    }
	
	private class FavoriteTask extends AsyncTask<Void, Integer ,Void>{
		RSSFeed favoriteFeed;
		ProgressDialog dialog;
		
		int id;
		public FavoriteTask(FirstScreen activity,String articleId) {
			
			this.id=Integer.parseInt(articleId.toString());
	
			dialog = new ProgressDialog(activity);
			dialog.setMessage("Loading Favorite...");
			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.setCancelable(true);
			dialog.setMax(100);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
		          public void onCancel(DialogInterface dialog) {
		        	  ft.cancel(true);
		        	  Toast.makeText(getApplicationContext(),
								"Loading canceled...", Toast.LENGTH_SHORT).show();
		          }
		    });

			dialog.show();
		}
		
		
		
		@Override
		protected Void doInBackground(Void... params) {
			FavoriteList.clear();
			//System.out.println(id+"<<<<<<<<<<<<<<<<<<<");
			favoriteFeed = getFeed("http://itweb.mobi/feed/itwebafrica/_load_africa.php/?source=android&tag=article&id="+id);
			if (favoriteFeed != null) {
				FavoriteList.add(favoriteFeed);
				publishProgress();
				if (isCancelled()) {
					FavoriteList.clear();
					if(dialog.isShowing()){
						dialog.dismiss();
					}						

					return null;
				}

				

			}

			return null;
		}
		
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			

		}

		@Override
		protected void onPostExecute(Void result) {
			 if(dialog.isShowing()){
					dialog.dismiss();
                 }	
			
			
			    Intent intent = new Intent(getApplicationContext(), SingleFavorite.class);
				intent.putExtra("id", 0);
				intent.putExtra("feedid", 0);
				startActivity(intent);

		}

	

		
	
	}
	
	
	public static RSSFeed getFeed(String urlToRssFeed) {
		try {

			URL url = new URL(urlToRssFeed);

			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setNamespaceAware(true);

			SAXParser parser = factory.newSAXParser();

			XMLReader xmlreader = parser.getXMLReader();

			RSSHandler theRssHandler = new RSSHandler();

			xmlreader.setContentHandler(theRssHandler);

			InputSource is = new InputSource(url.openStream());
			
			xmlreader.parse(is);

		
			return theRssHandler.getFeed();
		} catch (Exception ee) {
			
			return null;
		}
	}
	
	
	
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	fList.clear();
	    	finish();
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
}
